import requests

"""
建议main服务和每个node之间维护一个session，并保持心跳
"""


class RequestHandler:
    """requests函数封装"""

    def __init__(self):
        """session管理器"""
        self.session = requests.session()

    def visit(self, method, url, params=None, data=None, json=None, headers=None, **kwargs):
        """
        :param method: 请求方式
        :param url: 请求地址
        :param params: 字典或bytes，作为参数增加到url中
        :param data: data类型传参，字典、字节序列或文件对象，作为Request的内容
        :param json: json传参，作为Request的内容
        :param headers: 请求头，字典
        :param kwargs: 若还有其他的参数，使用可变参数字典形式进行传递
        :return:
        """
        return self.session.request(method, url, params=params, data=data, json=json, headers=headers, **kwargs,
                                    verify=False)

    def close_session(self):
        """关闭session"""
        self.session.close()

    @classmethod
    def send_node_msg(cls, method, node_url, data):
        res_info = None
        if method == 'get':
            res_info = requests.get(node_url, params=data)
        if method == 'post':
            res_info = requests.post(node_url, json=data)
        return res_info

    @classmethod
    def send_main_msg(cls, method, main_url, data):
        res_info = None
        if method == 'get':
            res_info = requests.get(main_url, params=data)
        if method == 'post':
            res_info = requests.post(main_url, json=data)
        return res_info


if __name__ == '__main__':
    # 以下是测试代码
    # post请求接口
    url = 'http://127.0.0.1:8000/user/login/'
    payload = {
        "username": "vivi",
        "password": "123456"
    }
    req = RequestHandler()
    login_res = req.visit("post", url, json=payload)
    print(login_res.text)
    req.close_session()
